package cn.iocoder.yudao.module.trade.service.config;

import cn.hutool.http.HttpUtil;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.module.trade.api.config.dto.AddressRespDTO;
import cn.iocoder.yudao.module.trade.controller.admin.config.vo.TradeConfigSaveReqVO;
import cn.iocoder.yudao.module.trade.convert.config.TradeConfigConvert;
import cn.iocoder.yudao.module.trade.dal.dataobject.config.TradeConfigDO;
import cn.iocoder.yudao.module.trade.dal.mysql.config.TradeConfigMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 交易中心配置 Service 实现类
 *
 * @author owen
 */
@Service
@Validated
public class TradeConfigServiceImpl implements TradeConfigService {

    @Resource
    private TradeConfigMapper tradeConfigMapper;

    @Override
    public void saveTradeConfig(TradeConfigSaveReqVO saveReqVO) {
        // 存在，则进行更新
        TradeConfigDO dbConfig = getTradeConfig();
        if (dbConfig != null) {
            tradeConfigMapper.updateById(TradeConfigConvert.INSTANCE.convert(saveReqVO).setId(dbConfig.getId()));
            return;
        }
        // 不存在，则进行插入
        tradeConfigMapper.insert(TradeConfigConvert.INSTANCE.convert(saveReqVO));
    }

    @Override
    public TradeConfigDO getTradeConfig() {
        List<TradeConfigDO> list = tradeConfigMapper.selectList();
        return CollectionUtils.getFirst(list);
    }

    @Override
    public boolean checkMessage(String content, String userId) {
        String body = HttpUtil.createPost("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined")
                .form("access_token",getToken())
                .form("userId", userId)
                .form("text",content).execute().body();
        String conclusionType = JSON.parseObject(body).getString("conclusionType");
        return "1".equals(conclusionType);
    }

    @Override
    public boolean checkImg(String img, String userId) {
        String body = HttpUtil.createPost("https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined")
                .form("access_token",getToken())
                .form("userId", userId)
                .form("imgUrl",img).execute().body();
        String conclusionType = JSON.parseObject(body).getString("conclusionType");
        return "1".equals(conclusionType);
    }

    @Override
    public boolean checkVoice(String voice, String userId) {
        String body = HttpUtil.createPost("https://aip.baidubce.com/rest/2.0/solution/v1/voice_censor/v3/user_defined")
                .form("access_token",getToken())
                .form("userId", userId)
                .form("fmt", "wav")
                .form("rate", 16000)
                .form("url",voice).execute().body();
        String conclusionType = JSON.parseObject(body).getString("conclusionType");
        return "1".equals(conclusionType);
    }

    @Override
    public boolean checkQrcode(String img) {
        String body = HttpUtil.createPost("https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode")
                .form("access_token",getQrCodeToken())
                .form("url",img).execute().body();
        Integer num = JSON.parseObject(body).getInteger("codes_result_num");
        if(num < 1){
            return  true;
        }
        String text =  JSON.parseObject(body).getJSONArray("codes_result").getJSONObject(0).getJSONArray("text").getString(0);
        return text.contains("https://u.wechat.com");
    }

    @Override
    public boolean checkImgQrcode(String img) {
        String body = HttpUtil.createPost("https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode")
                .form("access_token",getQrCodeToken())
                .form("url",img).execute().body();
        Integer num = JSON.parseObject(body).getInteger("codes_result_num");
        if(num < 1){
            return  true;
        }
        String text =  JSON.parseObject(body).getJSONArray("codes_result").getJSONObject(0).getJSONArray("text").getString(0);
        return text.contains("https://u.wechat.com");
    }

    @Override
    public boolean checkHasQrcode(String img) {
        String body = HttpUtil.createPost("https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode")
                .form("access_token",getQrCodeToken())
                .form("url",img).execute().body();
        Integer num = JSON.parseObject(body).getInteger("codes_result_num");
        if(num > 0){
            return  true;
        }
        return false;
    }

    @Override
    public AddressRespDTO getAddressByIp(String ip) {
        AddressRespDTO respDTO = new AddressRespDTO();
        respDTO.setProvince("中国");
        respDTO.setCity("中国");
        respDTO.setArea("中国");

        try {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization", "APPCODE " + "5f305b6a0eb8473a82df9387c0b78950");
            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("ip", ip);
            String rspStr = HttpUtil.createGet("https://ipcity.market.alicloudapi.com/ip/city/query").addHeaders(headers).form(paramMap).execute().body();
            JSONObject data = JSON.parseObject(rspStr).getJSONObject("data");
            JSONObject result = data.getJSONObject("result");
            String province = result.getString("prov");
            respDTO.setProvince(province);
        }catch(Exception e){
            e.printStackTrace();
        }
        return respDTO;
    }

    private String getQrCodeToken() {
        TradeConfigDO tradeConfigDO = getTradeConfig();
        String body = HttpUtil.createPost("https://aip.baidubce.com/oauth/2.0/token")
                .form("client_id", "VYOgvgy7xdptlBhP2iBdIWsy")
                .form("client_secret","HikEFknpZAK3H6MQRkqKDmDp8fHv8gI7")
                .form("grant_type","client_credentials").execute().body();
        return JSON.parseObject(body).getString("access_token");
    }

    private String getToken() {
        TradeConfigDO tradeConfigDO = getTradeConfig();
        String body = HttpUtil.createPost("https://aip.baidubce.com/oauth/2.0/token")
                .form("client_id", tradeConfigDO.getApiKey())
                .form("client_secret",tradeConfigDO.getSecretKey())
                .form("grant_type","client_credentials").execute().body();
        return JSON.parseObject(body).getString("access_token");
    }

}
